package com.example.service;

import cn.hutool.core.collection.CollUtil;
import com.example.entity.Department;
import com.example.entity.Department;
import com.example.exception.CustomException;
import com.example.mapper.DepartmentMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 部门信息业务处理
 **/
@Service
public class DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    /**
     * 新增
     */
    public void add(Department department) {
        // 1. 计算层级
        if (department.getPid() == null || department.getPid() == 0) {
            department.setPid(0);
            department.setLevel(1);
            department.setCode("1");          // 集团
        } else {
            Department parent = departmentMapper.selectById(department.getPid());
            if (parent == null) {
                throw new RuntimeException("父级部门不存在");
            }
            department.setLevel(parent.getLevel() + 1);

            // 2. 生成 code：取同级最大序号 +1
            String maxCode = departmentMapper.selectMaxCodeByPid(department.getPid());
            int next = maxCode == null ? 1 : Integer.parseInt(maxCode.substring(parent.getCode().length())) + 1;
            department.setCode(String.format("%s%02d", parent.getCode(), next));
        }
        departmentMapper.insert(department);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        departmentMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            departmentMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Department department) {
        if (department.getPid().equals(department.getId())) {
            throw new CustomException("上级部门不能是自己");
        }
        //上级部门不能是自己的下级部门
        Department parent = departmentMapper.selectById(department.getPid());
        List<Department> children = departmentMapper.selectByPid(department.getId());
        children.forEach(child -> {
            if (child.getId().equals(parent.getId())) {
                throw new CustomException("400", "上级部门不能是自己的子部门");
            }
        });
        departmentMapper.updateById(department);
    }

    /**
     * 根据ID查询
     */
    public Department selectById(Integer id) {
        return departmentMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Department> selectAll(Department department) {
        return departmentMapper.selectAll(department);
    }

    /**
     * 分页查询
     */
    public PageInfo<Department> selectPage(Department department, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Department> rootList = departmentMapper.selectByPid(0);

        // 直接复用
        Map<Integer, List<Department>> parentMap = buildParentMap();
        rootList.forEach(r -> r.setChildren(buildTree(parentMap, r.getId())));

        return PageInfo.of(rootList);
    }

    //    public List<Department> selectTree() {
//        // 效率比较低  我们应该怎么办？  lambda表达式做筛选
//        List<Department> list = departmentMapper.selectAll(null);
//        List<Department> rootList = list.stream().filter(department -> (department.getPid() == 0 || department.getPid() == null)).collect(Collectors.toList());
//        for (Department root : rootList) {
//            List<Department> level2List = list.stream().filter(department -> Objects.equals(department.getPid(), root.getId())).collect(Collectors.toList());
//            root.setChildren(level2List);
//            for (Department level2 : level2List) {
//                //  IO
//                List<Department> level3List = list.stream().filter(department -> Objects.equals(department.getPid(), level2.getId())).collect(Collectors.toList());
//                level2.setChildren(level3List);
//            }
//        }
//        return rootList;
//    }
    public List<Department> selectTree() {
        return buildTree(buildParentMap(), 0);
    }

    /**
     * 递归构建任意深度树
     *
     * @param parentMap 父→孩子映射
     * @param pid       当前要挂载的父id（从根 0 开始）
     */
    private List<Department> buildTree(Map<Integer, List<Department>> parentMap, Integer pid) {
        // 拿到当前父节点的所有孩子
        List<Department> children = parentMap.getOrDefault(pid, Collections.emptyList());
        for (Department child : children) {
            // 递归给每个孩子再找它的孩子
            child.setChildren(buildTree(parentMap, child.getId()));
        }
        return children;
    }

    private Map<Integer, List<Department>> buildParentMap() {
        PageHelper.clearPage(); // 防止被外层分页污染
        List<Department> all = departmentMapper.selectAll(null);
        if (CollUtil.isEmpty(all)) {
            return Collections.emptyMap();
        }
        return all.stream()
                .collect(Collectors.groupingBy(d -> Optional.ofNullable(d.getPid()).orElse(0)));
    }

    public List<Department> selectParent() {
        List<Department> list = departmentMapper.selectAll(null);
        return list.stream().filter(department -> department.getLevel() == 2 || department.getLevel() == 1).collect(Collectors.toList());
    }
}